package dcdroplet;

// Import Java JDK Classes
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.DecimalFormat;
import java.util.Date;

/**
* @author dca
*/
public class RollingFileAppenderProperties extends AppenderProperties {
	@Override
	public void log(String tag, String msg, String msgFmt, String className, long timeStamp) {
		try {
			// Check if we should roll the file over
			if(this.getFile().length() + msg.length() >= this.getSizeAsInt()) {
				// Roll the file over
				File parentDir = this.getFile().getParentFile();

				// Gett the log file properties
				String logFileAbsPath = this.getFile().getAbsolutePath();
				String logFileName = this.getFile().getName();
				String logFilePath = logFileAbsPath.replace(logFileName, "");

				// Get the log file without extension, if it even has one; or just the file name iteself.
				String logFileNameWithoutExt = (
					logFileName.contains(".") ?
					logFileName.substring(0, logFileName.lastIndexOf(".")) :
					logFileName
				);
				// Get the log file's extension, if it even has one; or empty string.
				String ext = (
					logFileName.contains(".") ?
					logFileName.substring(logFileName.lastIndexOf(".") + 1) :
					""
				);

				if(null != parentDir) {
					File[] allDirFiles = parentDir.listFiles();
					DecimalFormat rollFmt = new DecimalFormat("000");
					int maxRoll = 0;

					// Iterate through the files in the parent directory.
					for(File dirFile : allDirFiles) {
						String fileName = dirFile.getName();
						if(fileName.startsWith(logFileNameWithoutExt) && fileName.endsWith("." + ext)) {
							String numStr = fileName.replace(logFileNameWithoutExt, "").replace("." + ext, "");
							if(numStr.matches("\\d\\d\\d")) {
								int numRoll = Integer.parseInt(numStr);
								if(numRoll > maxRoll) {
									maxRoll = numRoll;
								} // END if
							} // END if
						} // END if
					} // END loop

					maxRoll++;

					File newFile = new File(logFilePath + logFileNameWithoutExt + rollFmt.format(maxRoll) + "." + ext);
					//System.out.printf("New Path: %s%n", newFile.getAbsolutePath());
					Files.move(
						Paths.get(this.getFile().toURI()),
						Paths.get(newFile.toURI()),
						StandardCopyOption.ATOMIC_MOVE
					);
				} // END if
			} // END if

			PrintStream out = new PrintStream(new FileOutputStream(this.getFile(), true));
			out.println(
				msgFmt.replace("${appender_name}", this.getAppenderName())
				      .replace("${class_name}", className)
				      .replace("${tag_name}",   tag)
				      .replace("${date}",       DATE.format(new Date(timeStamp)))
				      .replace("${time}",       TIME.format(new Date(timeStamp)))
				      .replace("${message}",    msg)
			);
			out.flush();
			out.close();
		} catch(FileNotFoundException fileExc) {
			System.err.printf("File not found: %s, for appender: %s%n", this.getFileDefinition(), this.getAppenderName());
		} catch(IOException ioExc) {
			System.err.printf("File write exception: %s, for appender: %s%n" + this.getFileDefinition(), this.getAppenderName());
		} // END try/catch
	} // END log
} // END class RollingFileAppenderProperties
